import store from '@/store'
import { handleServiceI18n } from '@/service/i18n'
import i18n from '@/i18n'
import { getParentsById } from '@/utils/common'

// 添加告警信息
const playAlarm = {
  playConfigList: [],
  speechList: [],
  saveSpeechList: [],
  currentData: null,
  speech: false,
  alarmConfigList: null,
  alarmAlert: [],
  systemAlert: false,
  speechMode: 'CUSTOM',
  notifyData: {},
  alreadyReset: false,
  init: function() {
    const alarmConfigData = store.getters.alarmConfigData
    this.alarmConfigList = alarmConfigData.alarmConfigList
    this.playConfigList = alarmConfigData.playConfigList || []
    this.speech = alarmConfigData.speech
    this.alarmAlert = alarmConfigData.alarmAlert
    this.systemAlert = alarmConfigData.systemAlert
    this.speechMode = alarmConfigData.speechMode
  },
  add: function(data) {
    const info = this.resetAdd(data)
    this.setFilter(info)
  },
  resetAdd(data) {
    // 新增告警和播报一轮完成后重置告警列表需要重置告警每项的数据
    if (!this.alarmConfigList) {
      this.init()
    }
    // 不用去重校验
    const levelData = this.alarmConfigList
      ? this.alarmConfigList.find(i => Number(i.level) === Number(data.alarmLevel))
      : {}
    data = { ...data, ...levelData }
    if (this.speechMode === 'LOOP') (data.number = 0)
    data.regionList = data.regionId
      ? (getParentsById(store.getters.regionTree, data.roomId || data.regionId, 'regionId') || []).reverse()
      : []
    if (this.systemAlert && this.alarmAlert.includes(Number(data.alarmLevel))) {
      store.commit('ADD_NOTIFY_LIST', data)
    }
    return data
  },
  setFilter(data) {
    // 过滤判断如果不需要播报的告警不不用添加到speechList列表了
    const { regionList, stationData, roomData } = this.getRegionObj(data)
    if (
      this.playConfigList.length === 0 ||
      data.speechType === 'DISABLE' ||
      regionList.length === 0 ||
      (roomData && roomData.status !== 'CONSIGN') ||
      (stationData && !roomData && stationData.status !== 'CONSIGN')
    ) return
    this.speechList.push(data)
    this.speechList
      .sort((a, b) => b.startTime - a.startTime)
      .sort((a, b) => Number(a.alarmLevel) - Number(b.alarmLevel))
    // 新添加的告警等级优先于当前播报的告警则立即执行更换播报
    if ((!this.currentData || Number(this.currentData.alarmLevel) > Number(data.alarmLevel))) {
      this.next()
    }
  },
  // 删除告警信息
  remove: function(data, next) {
    // 只有主动取消或者确认当前告警才会取消当前告警播报
    if (this.currentData && this.currentData.alarmId === data.alarmId && next) {
      window.speechSynthesis.cancel()
    }
    // 判断当取消告警时不影响正在播放的告警 因为其他告警为在speechList列表中
    if (this.currentData && this.currentData.alarmId === data.alarmId) {
      this.speechList = this.speechList.filter(i => i.alarmId !== data.alarmId)
      if (!this.speechList.length || !!next) {
        this.next()
      }
    }
  },
  // 播放下一个
  // 按等级顺序播放告警，会直接中断正在播放的语音
  next: function() {
    this.currentData = null
    // 如果是暂停状态，则继续播放剩下的语音
    window.speechSynthesis.resume()
    // 关闭语音播报的情况直接return
    if (!this.speech) return
    if (this.speechList.length) {
      this.alreadyReset = false
      this.play(this.speechList[0])
    } else {
      if (this.speechMode === 'LOOP' && !this.alreadyReset) {
        this.alreadyReset = true
        store.commit('RESET_PLAY_LIST')
        window.speechSynthesis.resume()
      }
    }
  },
  // 重置播放次数(用户重新设置了播放次数后用)
  resetTime: function() {
    this.init()
    window.speechSynthesis.cancel()
    this.speechList = this.speechList.map(i => {
      const levelData = this.alarmConfigList.find(j => Number(i.level) === Number(j.level))
      return { ...i, ...levelData }
    })
  },
  getRegionObj(data) {
    const regionList = data.regionList
    const stationList = regionList.filter(i => i.regionType === 'STATION')
    const roomList = regionList.filter(i => i.regionType === 'ROOM')
    const stationData = stationList[0] || null
    const roomData = roomList[0] || null
    return { regionList, stationList, roomList, stationData, roomData }
  },
  play: function(data) {
    const _this = this
    // 文字转语音，传入需要播放的str
    _this.currentData = data
    const { regionList, stationList, roomList } = this.getRegionObj(data)
    window.speechSynthesis.cancel()
    // 避免cancel杀掉后面新建的任务
    setTimeout(function() {
      let str = ''
      if (_this.playConfigList.includes('PLAY_LEVEL')) {
        str += data.alarmLabel
      }
      if (_this.playConfigList.includes('PLAY_REGION')) {
        str += regionList
          .filter(i => i.regionType === 'REGION')
          .map(i => i.regionName)
          .join('/')
      }
      if (_this.playConfigList.includes('PLAY_STATION')) {
        str += stationList.map(i => i.regionName).join('/')
      }
      if (_this.playConfigList.includes('PLAY_ROOM')) {
        str += roomList.map(i => i.regionName).join('/')
      }
      if (_this.playConfigList.includes('PLAY_DESC')) {
        if (data.device) {
          str += i18n.t('DEVICE_NAME_IS', { msg: _this.numberToWords(data.device.deviceName) })
        } else {
          str += i18n.t('DEVICE_ID_IS', { msg: _this.numberToWords(data.deviceId) })
        }
        str += handleServiceI18n(data.description)
      }
      if (str !== '') {
        // console.log('playStr', str)
        const msg = new SpeechSynthesisUtterance(str)
        msg.rate = 1
        msg.lang = localStorage.lang || 'zh-CN'
        msg.onend = function(e) {
          // console.log('播报完成', e)
          _this.next()
        }
        window.speechSynthesis.speak(msg)
      }
      if (data.number <= 1) {
        _this.remove(data)
      } else {
        data.number--
      }
    }, 100)
  },
  numberToWords(textName) { // 数字转文字读
    if (isNaN(textName) || !isFinite(textName)) {
      return textName
    }
    const ones = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    const strs = textName.split('')
    let str = ''
    strs.forEach(item => {
      str += ones[item]
    })
    return str
  }
}

export default playAlarm
